package com.zy.community.mini.service.index;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.community.common.core.domain.r.ZyResult;
import com.zy.community.community.domain.ZyOwner;
import com.zy.community.community.domain.vo.RoomStatus;
import com.zy.community.community.mapper.ZyOwnerMapper;
import com.zy.community.community.mapper.ZyOwnerRoomMapper;
import com.zy.community.community.mapper.ZyOwnerRoomRecordMapper;
import com.zy.community.framework.security.mini.MiniContextUtils;
import com.zy.community.web.controller.mini.life.dto.BindCommonDto;
import com.zy.community.web.controller.mini.life.dto.BindResultDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 我的房屋的服务
 */
@Service
public class MiniMyHouseService {
    @Resource
    private ZyOwnerRoomMapper zyOwnerRoomMapper;
    @Resource
    private ZyOwnerRoomRecordMapper zyOwnerRoomRecordMapper;

    @Resource
    private ZyOwnerMapper zyOwnerMapper;

    /**
     * 查询当前用户在该小区下所有的绑定信息
     *
     * @param communityId 小区Id
     * @return 绑定的结果
     */
    @Transactional(readOnly = true)
    public ZyResult<BindResultDto> findOwnerBindResult(Long communityId) {
        if (communityId == null) return ZyResult.fail(400, "小区Id不能为空");
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未携带身份信息");
        ZyOwner zyOwner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>().eq("owner_open_id", openId));
        if (zyOwner == null) return ZyResult.fail(404, "该用户不存在");
        List<BindCommonDto> bindResult = zyOwnerRoomMapper.findBindResult(zyOwner.getOwnerId(), communityId);

        BindResultDto bindResultDto = new BindResultDto();
        bindResult.forEach(bindDto -> {
            if (bindDto.getRoomStatus().equals(RoomStatus.Auditing)) {
                bindResultDto.getApplyList().add(bindDto);
            } else if (bindDto.getRoomStatus().equals(RoomStatus.Binding)) {
                bindResultDto.getBindList().add(bindDto);
            } else {
                //查询审批意见
                String lastedOpinion = zyOwnerRoomRecordMapper.findLastedOpinion(bindDto.getOwnerRoomId());
                if (!StringUtils.isEmpty(lastedOpinion)) {
                    bindDto.setRecordAuditOpinion(lastedOpinion);
                }
                bindResultDto.getRejectList().add(bindDto);
            }
        });
        return ZyResult.data(bindResultDto);
    }

}
